from rest_framework import viewsets, permissions, status, filters, generics
from rest_framework.decorators import action, api_view, permission_classes
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny, IsAuthenticated
from django.contrib.auth.models import User
from django_filters.rest_framework import DjangoFilterBackend
from .models import Objective, KeyResult, CheckIn, Team, Comment
from .serializers import (
    UserSerializer, ObjectiveSerializer, KeyResultSerializer,
    CheckInSerializer, TeamSerializer, CommentSerializer,
    RegisterSerializer
)

class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    自定义权限，只允许对象的所有者编辑它
    """
    def has_object_permission(self, request, view, obj):
        # 读取权限允许任何请求
        if request.method in permissions.SAFE_METHODS:
            return True
        
        # 写入权限只允许对象的所有者
        return obj.owner == request.user

class RegisterView(generics.CreateAPIView):
    """
    用户注册API视图
    """
    queryset = User.objects.all()
    permission_classes = (AllowAny,)
    serializer_class = RegisterSerializer

class UserViewSet(viewsets.ReadOnlyModelViewSet):
    """
    用户API视图，只允许查看，不允许修改
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.SearchFilter]
    search_fields = ['username', 'email', 'first_name', 'last_name']
    
    @action(detail=False, methods=['get', 'put'])
    def profile(self, request):
        """
        获取或更新当前登录用户的信息
        """
        if request.method == 'GET':
            serializer = self.get_serializer(request.user)
            return Response(serializer.data)
        elif request.method == 'PUT':
            serializer = self.get_serializer(request.user, data=request.data, partial=True)
            if serializer.is_valid():
                # 验证当前密码
                current_password = request.data.get('currentPassword')
                if not request.user.check_password(current_password):
                    return Response(
                        {"message": "当前密码不正确"},
                        status=status.HTTP_400_BAD_REQUEST
                    )
                
                # 如果提供了新密码，则更新密码
                new_password = request.data.get('newPassword')
                if new_password:
                    request.user.set_password(new_password)
                
                serializer.save()
                return Response(serializer.data)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class ObjectiveViewSet(viewsets.ModelViewSet):
    """
    目标API视图
    """
    queryset = Objective.objects.all()
    serializer_class = ObjectiveSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['status', 'owner', 'level', 'parent']
    search_fields = ['title', 'description']
    ordering_fields = ['created_at', 'start_date', 'end_date']
    
    def get_queryset(self):
        """
        可以通过查询参数过滤目标
        """
        queryset = Objective.objects.all()
        
        # 根据所有者过滤
        owner_id = self.request.query_params.get('owner_id', None)
        if owner_id:
            queryset = queryset.filter(owner_id=owner_id)
        
        # 根据父级目标过滤
        parent_id = self.request.query_params.get('parent_id', None)
        if parent_id:
            if parent_id == 'null':
                queryset = queryset.filter(parent__isnull=True)
            else:
                queryset = queryset.filter(parent_id=parent_id)
        
        # 根据目标层级过滤
        level = self.request.query_params.get('level', None)
        if level:
            queryset = queryset.filter(level=level)
        
        # 根据日期范围过滤
        start_date = self.request.query_params.get('start_date', None)
        end_date = self.request.query_params.get('end_date', None)
        
        if start_date:
            queryset = queryset.filter(start_date__gte=start_date)
        
        if end_date:
            queryset = queryset.filter(end_date__lte=end_date)
        
        return queryset
    
    def perform_create(self, serializer):
        """
        创建目标时自动设置所有者为当前用户
        """
        serializer.save(owner=self.request.user)
    
    @action(detail=True, methods=['post'])
    def add_comment(self, request, pk=None):
        """
        为目标添加评论
        """
        objective = self.get_object()
        serializer = CommentSerializer(data=request.data)
        
        if serializer.is_valid():
            serializer.save(
                created_by=request.user,
                objective=objective
            )
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        
    @action(detail=True, methods=['get'])
    def children(self, request, pk=None):
        """
        获取目标的所有子目标
        """
        objective = self.get_object()
        children = Objective.objects.filter(parent=objective)
        serializer = self.get_serializer(children, many=True)
        return Response(serializer.data)
    
    @action(detail=False, methods=['get'])
    def root(self, request):
        """
        获取所有顶级目标（没有父目标的目标）
        """
        root_objectives = Objective.objects.filter(parent__isnull=True)
        serializer = self.get_serializer(root_objectives, many=True)
        return Response(serializer.data)

class KeyResultViewSet(viewsets.ModelViewSet):
    """
    关键结果API视图
    """
    queryset = KeyResult.objects.all()
    serializer_class = KeyResultSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['status', 'objective', 'assignee']
    search_fields = ['title', 'description']
    ordering_fields = ['created_at', 'progress']
    
    def get_queryset(self):
        """
        可以通过查询参数过滤关键结果
        """
        queryset = KeyResult.objects.all()
        
        # 根据目标ID过滤
        objective_id = self.request.query_params.get('objective_id', None)
        if objective_id:
            queryset = queryset.filter(objective_id=objective_id)
        
        # 根据负责人过滤
        assignee_id = self.request.query_params.get('assignee_id', None)
        if assignee_id:
            queryset = queryset.filter(assignee_id=assignee_id)
        
        # 根据进度范围过滤
        min_progress = self.request.query_params.get('min_progress', None)
        max_progress = self.request.query_params.get('max_progress', None)
        
        if min_progress:
            queryset = queryset.filter(progress__gte=min_progress)
        
        if max_progress:
            queryset = queryset.filter(progress__lte=max_progress)
        
        return queryset
    
    @action(detail=True, methods=['post'])
    def add_check_in(self, request, pk=None):
        """
        为关键结果添加进度检查
        """
        key_result = self.get_object()
        
        # 设置上次进度为当前关键结果的进度
        request.data['previous_progress'] = key_result.progress
        
        serializer = CheckInSerializer(data=request.data)
        
        if serializer.is_valid():
            # 创建检查记录
            check_in = serializer.save(
                key_result=key_result,
                created_by=request.user
            )
            
            # 更新关键结果的当前进度
            key_result.progress = check_in.current_progress
            key_result.save()
            
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=True, methods=['post'])
    def add_comment(self, request, pk=None):
        """
        为关键结果添加评论
        """
        key_result = self.get_object()
        serializer = CommentSerializer(data=request.data)
        
        if serializer.is_valid():
            serializer.save(
                created_by=request.user,
                key_result=key_result
            )
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class CheckInViewSet(viewsets.ModelViewSet):
    """
    进度检查API视图
    """
    queryset = CheckIn.objects.all()
    serializer_class = CheckInSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ['key_result', 'created_by']
    ordering_fields = ['date', 'created_at']
    
    def perform_create(self, serializer):
        """
        创建进度检查时自动设置创建者为当前用户
        """
        key_result = serializer.validated_data.get('key_result')
        previous_progress = key_result.progress
        
        # 保存检查记录
        check_in = serializer.save(
            created_by=self.request.user,
            previous_progress=previous_progress
        )
        
        # 更新关键结果的进度
        key_result.progress = check_in.current_progress
        key_result.save()

class TeamViewSet(viewsets.ModelViewSet):
    """
    团队API视图
    """
    queryset = Team.objects.all()
    serializer_class = TeamSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.SearchFilter]
    search_fields = ['name', 'description']
    
    @action(detail=True, methods=['get'])
    def objectives(self, request, pk=None):
        """
        获取团队的所有目标
        """
        team = self.get_object()
        # 获取团队成员的所有目标
        objectives = Objective.objects.filter(owner__in=team.members.all())
        serializer = ObjectiveSerializer(objectives, many=True)
        return Response(serializer.data)

class CommentViewSet(viewsets.ModelViewSet):
    """
    评论API视图
    """
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def perform_create(self, serializer):
        """
        创建评论时自动设置创建者为当前用户
        """
        serializer.save(created_by=self.request.user)

class AuthTestView(APIView):
    """
    测试认证是否正常工作的视图
    """
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        return Response({
            'message': '认证成功',
            'user': request.user.username,
            'user_id': request.user.id
        })
